package drexel.loading;

import java.io.File;

import drexel.db.DataAccess;
import drexel.marshalling.Marshaller;
import drexel.marshalling.UnmarshallingException;
import drexel.model.Movie;

public class LoadingWorker extends Thread {

	private boolean continueToRun = true;
	private LoadingQueue queue = null;
	private LoadingNotifier notifier = null;
	private DataAccess dataAccess = null;
	private Marshaller marshaller = null;
	
	public LoadingWorker(LoadingQueue queue, LoadingNotifier notifier, 
		DataAccess dataAccess, Marshaller marshaller) {
		
		this.queue = queue;
		this.notifier = notifier;
		this.dataAccess = dataAccess;
		this.marshaller = marshaller;
	}
	
	public void run() {
		
		while (continueToRun) {
			
			File file = queue.getMovieFile();
			
			if (file != null) {
				
				process(file);
			}
		}
	}
	
	public synchronized void shutdown() {
		
		continueToRun = false;
		
		queue.done();
	}
	
	private void process (File file) {
		
		int tryAgainCounter = 0;
		
		try {
			
			Movie movie = marshaller.unmarshall(file);
			
			while (tryAgainCounter < 3) {
				
				if (dataAccess.saveMovie(movie)) {
				
					notifier.complete();
					
					break;
					
				} else {
				
					tryAgainCounter++;
					
					if (tryAgainCounter < 3) {
					
						try {
							
							Thread.sleep(30000);
							
						} catch (InterruptedException e) { }
						
						System.out.println("Trying " + movie.getTitle() + " Again ...");
					}
				}
			}
			
			if (tryAgainCounter == 3) {
				
				notifier.error("ERROR: Failed to load: " + file.getName() + " to database");
			}
		
		} catch (UnmarshallingException ume) {
			
			notifier.error("ERROR: Failed to parse file: " + file.getName() 
				+ " Error: " + ume.getMessage());
		}
	}
}
